from flask import Blueprint, jsonify
from flask_cors import cross_origin
from models import db
from sqlalchemy import text
import os
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

init_bp = Blueprint('init', __name__)

@init_bp.route('/api/init-database', methods=['GET'])
@cross_origin()
def init_database():
    try:
        logger.info("开始初始化数据库...")
        
        # 获取init.sql文件的路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        sql_file_path = os.path.join(os.path.dirname(current_dir), 'init.sql')
        logger.info(f"SQL文件路径: {sql_file_path}")
        
        if not os.path.exists(sql_file_path):
            logger.error(f"找不到init.sql文件: {sql_file_path}")
            return jsonify({
                'code': 404,
                'message': '找不到init.sql文件'
            }), 404

        # 读取SQL文件内容
        try:
            with open(sql_file_path, 'r', encoding='utf-8') as file:
                sql_content = file.read()
                logger.info("成功读取SQL文件")
        except Exception as e:
            logger.error(f"读取SQL文件失败: {str(e)}")
            return jsonify({
                'code': 500,
                'message': f'读取SQL文件失败: {str(e)}'
            }), 500

        # 执行SQL命令
        try:
            with db.engine.connect() as connection:
                # 将SQL文件内容按分号分割成单独的命令
                commands = [cmd.strip() for cmd in sql_content.split(';') if cmd.strip()]
                logger.info(f"共有 {len(commands)} 条SQL命令待执行")
                
                # 开始事务
                trans = connection.begin()
                try:
                    for i, command in enumerate(commands, 1):
                        try:
                            # 使用text()函数处理SQL语句
                            connection.execute(text(command))
                            logger.info(f"成功执行第 {i} 条SQL命令")
                        except Exception as e:
                            logger.error(f"执行第 {i} 条SQL命令失败: {str(e)}")
                            raise
                    
                    # 提交事务
                    trans.commit()
                    logger.info("所有SQL命令执行完成，事务已提交")
                except Exception as e:
                    # 发生错误时回滚事务
                    trans.rollback()
                    logger.error(f"执行SQL命令失败，事务已回滚: {str(e)}")
                    raise

            return jsonify({
                'code': 200,
                'message': '数据库初始化成功'
            })

        except Exception as e:
            return jsonify({
                'code': 500,
                'message': f'执行SQL命令失败: {str(e)}'
            }), 500

    except Exception as e:
        logger.error(f"初始化数据库时发生未知错误: {str(e)}")
        return jsonify({
            'code': 500,
            'message': f'初始化数据库失败: {str(e)}'
        }), 500 